package com.my.lab.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.my.lab.R;
import com.my.lab.adapter.AppAdapter;
import com.my.lab.util.AppSizeUtil;
import com.my.lab.util.MyAdapter;

public class AppActivity extends Activity {

    private ListView appListview;

    private MyAdapter appAdapter;

    private ProgressBar pbar;

    private TextView tvError;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_listview_layout);
        initUi();
        initAppData();
    }

    private void initUi() {
        appListview = (ListView) findViewById(R.id.app_list);
        pbar = (ProgressBar) findViewById(R.id.progress_bar);
        tvError = (TextView) findViewById(R.id.tv_error);
    }

    private void initAppData() {
        new getAppTask().execute();

    }

    private class getAppTask extends AsyncTask<Void, Void, List<HashMap<String, Object>>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pbar.setVisibility(View.VISIBLE);
            tvError.setVisibility(View.GONE);
            appListview.setVisibility(View.GONE);
        }

        @Override
        protected List<HashMap<String, Object>> doInBackground(Void... params) {
            List<HashMap<String, Object>> result = getAppInfo(getApplicationContext());
            return result;
        }

        @Override
        protected void onPostExecute(final List<HashMap<String, Object>> result) {
            super.onPostExecute(result);
            pbar.setVisibility(View.GONE);
            if (result != null) {
                appListview.setVisibility(View.VISIBLE);
                if (appAdapter == null) {
                    appAdapter = new AppAdapter(getApplicationContext(), result);
                    appListview.setAdapter(appAdapter);
                } else {
                    appAdapter.updateListData(result);
                }
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... arg0) {
                        AppSizeUtil appSizeUtil = new AppSizeUtil();
                        for (int i = 0; i < result.size(); ++i) {
                            HashMap<String, Object> item = result.get(i);
                            Long l = null;
                            try {
                                l = appSizeUtil.queryPacakgeSize(getApplicationContext(), (String) item.get("packageName"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            item.put("appSize", getSizeLong2String(l));
                            Log.d("", "appName:"+item.get("appName")+",appSize:"+item.get("appSize"));
                            mHandler.sendEmptyMessage(0);
                        }
                        return null;
                    }

                    protected void onPostExecute(Void result) {
                    };
                }.execute();
            } else {
                tvError.setVisibility(View.VISIBLE);
            }
        }

    }
    
    private Handler mHandler = new  Handler() {
        @Override
        public void handleMessage(Message msg) {
            ((AppAdapter) appListview.getAdapter()).notifyDataSetChanged();
            super.handleMessage(msg);
        }
    };

    /**
     * 获取手机所以应用的信息
     * 
     * @param context
     * @return Map中的key：appName,versionName,packageName,versionCode,appIcon<br>
     *         appName:应用名称<br>
     *         versionName:应用版本<br>
     *         packageName:应用包名<br>
     *         versionCode:版本号<br>
     *         appIcon:应用图标<br>
     */
    public ArrayList<HashMap<String, Object>> getAppInfo(Context context) {
        ArrayList<HashMap<String, Object>> appInfo = new ArrayList<HashMap<String, Object>>();
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("appName", packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString());
                item.put("versionName", packageInfo.versionName);
                item.put("packageName", packageInfo.packageName);
                item.put("versionCode", packageInfo.versionCode);
                item.put("appIcon", packageInfo.applicationInfo.loadIcon(context.getPackageManager()));
                appInfo.add(item);
            }
        }
        return appInfo;
    }

    /**
     * 将应用大小的long值转换为字符形式
     * 
     * @param size
     * @return
     */
    public static String getSizeLong2String(Long size) {
        String suffix = "MB";
        Float f = size.floatValue();
        String s = size.toString();
        if (s.length() >= 7) {
            f = f / 1024 / 1024;
        } else {
            suffix = "KB";
            f = f / 1024;
        }
        s = f.toString();
        int c = s.indexOf(".");
        if (s.substring(c).length() == 2)
            s = s.concat("0");
        return s.substring(0, c) + s.substring(c, c + 3) + suffix;
    }
}
